using System.Collections;
using System.Collections.Generic;
using System.Transactions;
using UnityEngine;

public class WeaponController : MonoBehaviour
{
    public GameObject weaponRot;

    public Transform weaponMuzzle;

    public GameObject muzzleFlashPrefab;

    public float delayBetweenShots = 0.1f;

    private float _lastShotTime = Mathf.NegativeInfinity;
    public bool isWeaponActive { get; private set; }
    public GameObject owner { get; set; }
    public GameObject sourcePrefab { get; set; }

    private Animator anim;

    public ProjectileBase projectilePrefab;
    public Vector3 muzzleWorldVelocity { get; private set; }
    public void showWeapon(bool show)
    {
        weaponRot.SetActive(show);
        isWeaponActive = (show);
    }

    public bool HandleShootInput(bool inputHeld)
    {
        if (inputHeld)
        {
            return TryShoot();
        }
        return false;
    }

    private bool TryShoot()
    {
        if (_lastShotTime + delayBetweenShots < Time.time)
        {
            HandleShoot();
            print("shot");
            
            return true;
        }
        return false;
    }

    private void HandleShoot()
    {
        if (projectilePrefab != null)
        {
            Vector3 shotDirection = weaponMuzzle.forward;
            ProjectileBase newProjectile = Instantiate(projectilePrefab, weaponMuzzle.position, weaponMuzzle.rotation,
                weaponMuzzle.transform);
            
            newProjectile.shoot(this);
        }

        if (muzzleFlashPrefab != null)
        {
            GameObject muzzleFlashInstance = Instantiate(muzzleFlashPrefab, weaponMuzzle.position,
                weaponMuzzle.rotation, weaponMuzzle.transform);
            Destroy(muzzleFlashInstance,3);
        }
        _lastShotTime = Time.time;
    }
}
